# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  
  def post_edit_path(post)
    html = ''
    if post.class == CommonPost
      html << link_to('编辑', edit_common_post_path(post.community.district, post.community, post))
    end
    if post.class == GroupPost
      html << link_to('编辑', edit_group_post_path(post.group, post))
    end
    if post.class == SitePost
      html << link_to('编辑', edit_site_post_path(post.site, post))
    end
    html
  end
  
  def post_delete_path(post)
    html = ''
    if post.class == CommonPost
      html << link_to('删除', common_post_path(post.community.district, post.community, post), :confirm => "Are you sure?", :method => :delete)
    end
    if post.class == GroupPost
      html << link_to('删除', group_post_path(post.group, post), :confirm => "Are you sure?", :method => :delete)
    end
    if post.class == SitePost
      html << link_to('删除', site_post_path(post.site, post), :confirm => "Are you sure?", :method => :delete)
    end
    html
  end
  
  def post_reply_delete_path(reply)
    html = ''
    if reply.post.class == CommonPost
      html << link_to('删除', community_post_reply_path(reply.post.community.district, reply.post.community, reply.post, reply), :confirm => "Are you sure?", :method => :delete)
    end
    if reply.post.class == GroupPost
      html << link_to('删除', group_post_reply_path(reply.post.group, reply.post, reply), :confirm => "Are you sure?", :method => :delete)
    end
    if reply.post.class == SitePost
      html << link_to('删除', site_post_reply_path(reply.post.site, reply.post, reply), :confirm => "Are you sure?", :method => :delete)
    end
    html
  end
  
  def url_for_post(post)
    if post.class == CommonPost
      return common_post_path(post.community.district, post.community, post)
    end
    if post.class == GroupPost
      return group_post_path(post.group, post)
    end
    if post.class == SitePost
      return site_post_path(post.site, post)
    end
  end
  
  def post_path(post, title = nil)
    html = ''
    if title.nil?
      title = post.title
    end
    html << link_to("#{title}", url_for_post(post))
  end
  
  def post_parent_path(post)
    html = ''
    if post.class == CommonPost
      html << '类别 ' << link_to("#{post.post_category.title}", cats_community_path(post.community.district, post.community, :cat => post.post_category))
    end
    if post.class == GroupPost
      html << '小组 ' << link_to("#{post.group.title}", group_path(post.group))
    end
    if post.class == SitePost
      html << '场所 ' << link_to("#{post.site.title}", site_path(post.site))
    end
    html
  end
  
  def return_post_path(post)
    html = ''
    if post.class == CommonPost
      html << '<li>' << image_tag("house_go.png", :align=>"absmiddle") << link_to("返回#{post.community.title}", community_path(post.community.district, post.community)) << '</li>'
    end
    if post.class == GroupPost
      html << '<li>' << image_tag("house_go.png", :align=>"absmiddle") << link_to("返回小组首页", groups_path) << '</li>'
      html << '<li>' << image_tag("house_go.png", :align=>"absmiddle") << link_to("返回#{post.group.title}", group_path(post.group)) << '</li>'
    end
    if @post.class == SitePost
      html << '<li>' << image_tag("house_go.png", :align=>"absmiddle") << link_to("返回#{post.site.title}", site_path(post.site)) << '</li>'
    end
    html
  end
  
  def current_position_post_path(post)
    html = ' » '
    if post.class == CommonPost
      html << link_to("#{post.community.district.title}", district_path(post.community.district))
      html << ' » '
      html << link_to("#{post.community.title}", community_path(post.community.district, post.community))
    end
    if post.class == SitePost
      html << link_to("#{post.site.title}", site_path(post.site))
    end
    if post.class == GroupPost
      html << link_to("小组", groups_path)
      html << ' » '
      html << link_to("#{post.group.title}", group_path(post.group))
    end
    html
  end
  
  def rss_post_path(post)
    html = ''
    if post.class == CommonPost
      html << feed_icon_tag(post.title, formatted_common_post_path(@post.community.district, @post.community, @post, :rss))
    end
    if post.class == SitePost
      html << feed_icon_tag(post.title, formatted_site_post_path(@post.site, @post, :rss))
    end
    if post.class == GroupPost
      html << feed_icon_tag(post.title, formatted_group_post_path(@post.group, @post, :rss))
    end
    html
  end
  
  def fckeditor_text_field(object, method, options = {})
    text_area(object, method, options ) +
    javascript_tag( "var oFCKeditor = new FCKeditor('" + object + "_" + method + "');oFCKeditor.Config['ToolbarStartExpanded'] = false;oFCKeditor.ToolbarSet = 'Basic';oFCKeditor.ReplaceTextarea()" )
  end
  
  def top_post_categories
    @categories = PostCategory.find(:all, :conditions => [ "parent_id = 0"], :order => "position DESC")
  end
  
  def tag_cloud(tags, classes)
    #tags = Tag.tags(:limit => 100, :order => "updated_at desc")
    max, min = 0, 0
    tags.each { |t|
      max = t.count.to_i if t.count.to_i > max
      min = t.count.to_i if t.count.to_i < min
    }

    divisor = ((max - min) / classes.size) + 1

    tags.each { |t|
      yield t.name, classes[(t.count.to_i - min) / divisor]
    }
  end
  
  def tag_cloud_same_style(tags)\
    max, min = 0, 0
    tags.each { |t|
      max = t.count.to_i if t.count.to_i > max
      min = t.count.to_i if t.count.to_i < min
    }

    divisor = ((max - min) / classes.size) + 1

    tags.each { |t|
      yield t.name, classes[(t.count.to_i - min) / divisor]
    }
  end

  def site_title
    if @page_title.nil?
      @page_title = '您这儿'
    else
      @page_title = @page_title + ' - 您这儿'
    end
  end
  
  def local_date(date)
    if !date.nil?
        
        date = date.since(3600*8)
        date.year.to_s + "/" + date.month.to_s + "/" + date.day.to_s + " " + date.hour.to_s + ":" + date.min.to_s 
    end
  end
  
  def rss_local_date(date)
    if !date.nil?
        date = date.since(3600*8)
    end
  end
  
  def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
    from_time = from_time.to_time if from_time.respond_to?(:to_time)
    to_time = to_time.to_time if to_time.respond_to?(:to_time)
    distance_in_minutes = (((to_time - from_time).abs)/60).round
  
    case distance_in_minutes
      when 0..1           then (distance_in_minutes==0) ? 'a few seconds ago'[] : '1 minute ago'[]
      when 2..59          then "{minutes} minutes ago"[:minutes_ago, distance_in_minutes]
      when 60..90         then "1 hour ago"[]
      when 90..1440       then "{hours} hours ago"[:hours_ago, (distance_in_minutes.to_f / 60.0).round]
      when 1440..2160     then '1 day ago'[] # 1 day to 1.5 days
      when 2160..2880     then "{days} days ago"[:days_ago, (distance_in_minutes.to_f / 1440.0).round] # 1.5 days to 2 days
      else from_time.strftime("%b %e, %Y  %l:%M%p"[:datetime_format]).gsub(/([AP]M)/) { |x| x.downcase }
    end
  end
  
  def unread_messages_num
    query = ""
    query << "select count(*) as num"
    query << " from messages, user_messages, users"
    query << " where messages.id = user_messages.message_id"
    query << " and user_messages.from_id = users.id"
    query << " and user_messages.is_read = 'f'"
    query << " and user_messages.user_id = '" 
    query << current_user.id.to_s
    query << "'"
    messages = Message.find_by_sql [query]
    messages[0].num
  end
  
  def categoriy_tags(category)
    tags = Tag.tags(:limit => 100, :order => "updated_at desc", :type => "common", :which => category.id)
  end
  
  def categoriy_and_district_tags(category, district)
    tags = Tag.tags(:limit => 100, :order => "updated_at desc", :type => "common", :geog => "district", :geog_id =>district.id, :which => category.id)
  end
  
  def district_tags(district)
    tags = Tag.tags(:limit => 100, :order => "updated_at desc", :type => "common", :geog => "district", :geog_id =>district.id)
  end
       
  def community_tags(community)
    tags = Tag.tags(:limit => 100, :order => "updated_at desc", :type => "common", :geog => "community", :geog_id =>community.id)
  end
    
  def posts_of_same_user(post)
    if post.class == CommonPost
      posts = CommonPost.find(:all, :conditions => [ "user_id = ? and id != ? and post_category_id = ?", post.user.id, post.id, post.post_category_id], :order => "replied_at desc limit 6")
    end
    if post.class == GroupPost
      posts = GroupPost.find(:all, :conditions => [ "user_id = ? and id != ? and group_id = ?", post.user.id, post.id, post.group_id], :order => "replied_at desc limit 6")
    end
    if post.class == SitePost
      posts = SitePost.find(:all, :conditions => [ "user_id = ? and id != ? and site_id = ?", post.user.id, post.id, post.site_id], :order => "replied_at desc limit 6")
    end
    posts
  end
  
  def posts_of_same_cat(post)
    if post.class == CommonPost
      posts = CommonPost.find(:all, :conditions => [ "id != ? and post_category_id = ?", post.id, post.post_category_id], :order => "replied_at desc limit 6")
    end
    if post.class == GroupPost
      posts = GroupPost.find(:all, :conditions => [ "id != ? and group_id = ?", post.id, post.group_id], :order => "replied_at desc limit 6")
    end
    if post.class == SitePost
      posts = SitePost.find(:all, :conditions => [ "id != ? and site_id = ?", post.id, post.site_id], :order => "replied_at desc limit 6")
    end
    posts
  end
    
  def feed_icon_tag(title, url)
    (@feed_icons ||= []) << { :url => url, :title => title }
    link_to image_tag('feed-icon.png', :size => '14x14', :alt => "Subscribe to #{title}"), url
  end

  private
  ## Extend options_for_javascript to handle hashmap of hashmap
  def options_for_javascript(options)
    '{' + options.map {|k, v|  v.kind_of?(Hash) ? "#{k}:#{options_for_javascript(v)}" : "#{k}:#{v}"}.sort.join(', ') + '}'
  end  
  
end
